
import openpyxl
from datetime import datetime
import sys

if len(sys.argv) < 2:
	print('请在命令行中添加文件名，命令格式如下:\npython kw_split.py keywords.xlsx')
	sys.exit()

file = sys.argv[1] #'keywords.xlsx'

wb = openpyxl.load_workbook(file)
sheet = wb['Sheet']
row = sheet.max_row
col = sheet.max_column
print(f'开始处理数据，共有{row}行，{col}列')


#如果同名sheet已经存在，先删除
sheet2_name = 'Result'
if 'Result' in wb.sheetnames:
	sheet2 = wb[sheet2_name]
	wb.remove(sheet2)

#新建sheet
sheet2 = wb.create_sheet(sheet2_name)

#把关键词写入到sheet
count = 0
for i in range(1, row+1):
	#获取关键词字符串
	kw_str = sheet.cell(i, col).value
	keywords = kw_str.split(';')
	for kw in keywords:
		count += 1

		#添加序号
		sheet2.cell(count, 1, count-1)

		#处理中间的列，支持多行
		for j in range(2, col):
			value =  sheet.cell(i, j).value
			sheet2.cell(count, j, value)

		#加上keyword
		sheet2.cell(count, col, kw)

#打印生成的行数
print(f'处理完毕，共生成{count}行数据')

#生成新的文件名字
now = datetime.now()
new_file_name = now.strftime('%Y%m%d-%H%M%S')
wb.save(new_file_name + '.xlsx')